<template>
  <div>
    <!-- 面包屑导航 separator是以>分割 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面板，一个方形区域 -->
    <el-card class="box-card">
      <el-row :gutter="24">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryinfo.query"
              clearable
              @clear="getuserlist"
            >
              <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="12">
          <el-button type="success" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userlist" style="width: 100%" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="120"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="300"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="120">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="210">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" @click="showedit(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" @click="deluser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" @click="showroledialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 对话框 dialogVisible为true就显示  dialogVisible为false 就隐藏 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="closedialog">
      <el-form ref="formref" :model="addform" :rules="formrules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addform.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑用户" :visible.sync="editdialogVisible" width="50%">
      <el-form ref="formref" :model="editform" :rules="formrules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editform.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edituser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="roledialogVisible" width="30%">
      <div>姓名：{{roleinfo.username}}</div>
      <div>角色名称：{{roleinfo.role_name}}</div>
      <el-select v-model="selectrole" placeholder="请选择">
        <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addrole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 校验规则 ele固定写法
    // 自定义规则在data里定义函数
    // 在规则里 { validator: checkemail, trigger: "blur" }
    //验证邮箱
    var checkemail = (rule, value, callback) => {
      // 正则表达式
      //\w一个数字字母下划线  \d一个数字  +1个以上 ?0或1个 *0个以上
      const regemail = /^\w+@\w+\.\w+$/;
      // regemail.test(值)，匹配成功返回true 错误返回false
      if (!regemail.test(value)) {
        //不匹配
        return callback(new Error("邮箱格式不正确"));
      }
      return callback(); //正确
    };
    //验证电话
    var checkmobile = (rule, value, callback) => {
      const regmobile = /^1\d{10}$/;
      if (!regmobile.test(value)) {
        //不匹配
        return callback(new Error("电话格式不正确"));
      }
      return callback(); //正确
    };
    return {
      //query：要搜索的名字
      queryinfo: { query: "", pagenum: 1, pagesize: 2 },
      userlist: [],
      total: 0,
      mg_state: false,
      dialogVisible: false, //对话框隐藏
      editdialogVisible: false,
      roledialogVisible: false, //对话框隐藏
      roleinfo: {},
      rolelist: [],
      selectrole: "",
      addform: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editform: {},
      formrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度为3-10位", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度为3-10位", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkemail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getuserlist();
  },
  methods: {
    // 添加角色 获取角色的id 发送ajax，去分配
    async addrole() {
      if (!this.selectrole) {//没选
        return this.$message.error("请选择角色");
      }
      // console.log(this.selectrole);
      let { data: res } = await this.$http.put(`users/${this.roleinfo.id}/role`, {
        rid: this.selectrole
      });
      if (res.meta.status != 200) {
        return this.$message.error("分配角色失败");
      }
      this.$message.success("分配角色成功");
      this.getuserlist();//重新渲染
      this.roledialogVisible = false;
    },
    // 显示分配角色框
    async showroledialog(role) {
      // console.log(role);
      this.roleinfo = role;
      let { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        return this.$message.error("获取角色失败");
      }
      this.rolelist = res.data;
      this.roledialogVisible = true; //让分配角色对话框显示
    },
    // 删除用户
    async deluser(id) {
      let result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // reult值为confirm时就是确认删除，cancel就是取消
      if (result != "confirm") return this.$message.info("取消删除成功");
      // 确定删除则发ajax
      let { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      // 删除成功重新发ajax渲染页面
      this.getuserlist();
    },
    //显示编辑用户窗口
    async showedit(id) {
      // 显示编辑页面
      let { data: res } = await this.$http.get("users/" + id);
      // console.log(res);
      this.editform = res.data;
      this.editdialogVisible = true;
    },
    // 编辑
    edituser() {
      // $refs这里是预验证的写法
      this.$refs.formref.validate(async valid => {
        console.log(valid); //通过true，失败false
        if (!valid) return;
        let { data: res } = await this.$http.put("users/" + this.editform.id, {
          email: this.editform.email,
          mobile: this.editform.mobile
        });
        if (res.meta.status != 200) return this.$message.error("编辑失败");
        this.$message.success("编辑成功");
        // 编辑成功后再重新获取数据渲染页面
        this.getuserlist();
        // 编辑成功点击隐藏对话框
        this.editdialogVisible = false;
      });
    },
    // 添加用户
    adduser() {
      // $refs这里是预验证的写法
      this.$refs.formref.validate(async valid => {
        console.log(valid); //通过true，失败false
        if (!valid) return;
        // 成功发ajax
        let { data: res } = await this.$http.post("users", this.addform);
        if (res.meta.status != 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        // 添加成功后再获取数据渲染页面
        this.getuserlist();
        // 关闭对话框
        this.dialogVisible = false;
      });
    },
    closedialog() {
      // 清空表单 ele里内置的方法
      this.$refs.formref.resetFields();
    },
    async getuserlist() {
      let { data: res } = await this.$http.get("users", {
        params: this.queryinfo
      });
      //   console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("获取失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newsize) {
      this.queryinfo.pagesize = newsize;
      this.getuserlist();
    },
    handleCurrentChange(newpage) {
      this.queryinfo.pagenum = newpage;
      this.getuserlist();
    },
    async changeSwitch(userinfo) {
      console.log(userinfo);
      let { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("设置用户状态失败");
        userinfo.mg_state = !userinfo.mg_state;
      }
      this.$message.success("更新用户状态成功！");
    }
  }
};
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 10px;
}
.el-table {
  margin-top: 10px;
}
</style>


